//
//  MainViewController.swift
//  sinaWB
//
//  Created by Macdav on 16/4/6.
//  Copyright © 2016年 Dav. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {
    
    
    //MARK 监听方法
    //    如果单纯使用pribate,程序会崩溃,因为运行循环无法发送消息,加了@obj就可以了
    @objc private func clickComposeButton(){
        print("点我了")
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        addChildViewControllers()
        
        setupComposedButton()
        
    }
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        tabBar.bringSubviewToFront(composedButton)
    }
    //懒加载无处不在,因为所有的控件都是延迟加载的
    //    懒加载按钮
    private lazy var composedButton: UIButton = UIButton(
        imageName: "tabbar_compose_icon_add",
        backImageName: "tabbar_compose_button")
}

///MARK  -设置界面
extension MainViewController{
    
    
    /**
     设置撰写按钮
     */
    private func setupComposedButton(){
        // 1 添加按钮
        tabBar.addSubview(composedButton)
        // 2 设置按钮
        let count = childViewControllers.count
        //       按钮的宽
        let w = tabBar.bounds.width / CGFloat(count) - 1
        //        3 设置按钮的frame
        composedButton.frame = CGRectInset(tabBar.bounds, 2 * w, 0)
        //        4 设置按钮的监听方法
        composedButton.addTarget(self, action: "clickComposeButton", forControlEvents:.TouchUpInside)
        
    }
    /**
     添加所有子控制器
     */
    private func addChildViewControllers() {
        tabBar.tintColor = UIColor.orangeColor()
        addChildViewController(HomeViewController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(MessageViewController(), title: "消息", imageName: "tabbar_message_center")
        addChildViewController(UIViewController())
        addChildViewController(DiscoverViewController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(ProfilesViewController(), title: "我", imageName: "tabbar_profile")
    }
    //    添加子控制器
    private func addChildViewController(vc:UIViewController,title:String,imageName:String) {
    
        vc.title = title
        vc.tabBarItem.image = UIImage(named: imageName)
        let nav = UINavigationController(rootViewController: vc)

        addChildViewController(nav)
    }
    
}
